package cc.geeksearch.ble

import android.content.Context
import android.content.SharedPreferences
import cc.geeksearch.ble.bean.DeviceBean
import org.json.JSONArray
import org.json.JSONObject

class WalleDeviceSp(context: Context) {
    private val PREF_NAME = "WalleDevices"
    private val KEY_DEVICE = "devices"
    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    private val editor: SharedPreferences.Editor = sharedPreferences.edit()

    /**
     * 保存字符串数据到 SharedPreferences
     * @param key 键
     * @param value 值
     */
    fun saveString(key: String, value: String) {
        editor.putString(key, value)
        editor.apply()
    }

    /**
     * 从 SharedPreferences 获取字符串数据
     * @param key 键
     * @param defaultValue 默认值
     * @return 存储的字符串数据，如果未找到则返回默认值
     */
    fun getString(key: String, defaultValue: String): String {
        return sharedPreferences.getString(key, defaultValue) ?: defaultValue
    }

    /**
     * 更新绑定的所有设备
     */
    fun updateDevices(devices: MutableList<DeviceBean>) {
        if (devices.isEmpty()) {
            editor.clear()
            editor.apply()
            return
        }
        val jsonArray = JSONArray()
        for (device in devices) {
            val jsonObject = JSONObject()
            jsonObject.put("address", device.address)
            jsonObject.put("name", device.name)
            jsonObject.put("remark", device.remark)
            jsonArray.put(jsonObject)
        }
        editor.putString(KEY_DEVICE, jsonArray.toString())
        editor.apply()
    }

    fun deleteAllDevices() {
        editor.clear()
        editor.apply()
    }

    /**
     * 获取所有设备
     */
    fun getDevices(): MutableList<DeviceBean> {
        val devices = mutableListOf<DeviceBean>()
        val jsonString = sharedPreferences.getString(KEY_DEVICE, "")
        if (jsonString.isNullOrEmpty()) {
            return devices
        }
        val jsonArray = JSONArray(jsonString)
        for (i in 0 until jsonArray.length()) {
            val jsonObject = jsonArray.getJSONObject(i)
            val address = jsonObject.getString("address")
            val name = jsonObject.optString("name","")
            var remark = jsonObject.optString("remark","")
            if (remark.isEmpty()) {
                remark = ""
            }
            val device = DeviceBean(address, name, DeviceStatus.NOT_CONNECTED, remark)
            devices.add(device)
        }
        return devices
    }
}